package edu.hawaii.ics414;

import java.util.concurrent.TimeUnit;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import edu.hawaii.ics414.CurrentUser;

public class MainActivity extends FragmentActivity {

  /**
   * The {@link android.support.v4.view.PagerAdapter} that will provide fragments for each of the
   * sections. We use a {@link android.support.v4.app.FragmentPagerAdapter} derivative, which will
   * keep every loaded fragment in memory. If this becomes too memory intensive, it may be best to
   * switch to a {@link android.support.v4.app.FragmentStatePagerAdapter}.
   */
  SectionsPagerAdapter mSectionsPagerAdapter;

  /**
   * The {@link ViewPager} that will host the section contents.
   */
  ViewPager mViewPager;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // Create the adapter that will return a fragment for each of the three
    // primary sections
    // of the app.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
  }

  @Override
  public boolean onPrepareOptionsMenu(Menu menu) {
    if (CurrentUser.isLoggedIn) {
      menu.findItem(R.id.menu_profile).setEnabled(true);
      menu.findItem(R.id.menu_login).setEnabled(false);
    }
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.menu_profile:
      //Log.wtf("", CurrentUser.username);
      Intent myIntentProfile = new Intent(MainActivity.this, ProfileView.class);
      startActivity(myIntentProfile);
      return true;
    case R.id.menu_search:
      Intent myIntent = new Intent(MainActivity.this, SearchView.class);
      startActivity(myIntent);
      return true;
    case R.id.menu_login:
      final Dialog dialog = new Dialog(MainActivity.this);
      dialog.setContentView(R.layout.login_dialog);
      dialog.setTitle("Sign In");
      dialog.setCancelable(true);
      ImageButton facebookLogin = (ImageButton) dialog.findViewById(R.id.facebookLogin);
      Button button = (Button) dialog.findViewById(R.id.signUpButton);
      Button loginButton = (Button) dialog.findViewById(R.id.loginButton);

      /*
       * Sets up the new account button
       */
      button.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
          Intent myIntent = new Intent(MainActivity.this, NewAccountView.class);
          startActivity(myIntent);
        }
      });

      /*
       * Sets up the login button
       */
      loginButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

          EditText loginUsernameText = (EditText) dialog.findViewById(R.id.usernameInput);
          EditText loginPasswordText = (EditText) dialog.findViewById(R.id.passwordInput);

          String loginUsername = loginUsernameText.getText().toString().trim();
          String loginPassword = loginPasswordText.getText().toString();
          String tryLogin = "";

          try {
            tryLogin = new Login().execute(loginUsername, loginPassword).get(5, TimeUnit.SECONDS);
          }
          catch (Exception e) {
            Toast.makeText(MainActivity.this, "Something went wrong. Try again", Toast.LENGTH_LONG)
                .show();
          }

          try {
            boolean loginSuccess = Boolean.parseBoolean(tryLogin.trim());
            if (loginSuccess) {
              Toast.makeText(MainActivity.this, "LOGIN SUCCESS", Toast.LENGTH_LONG).show();
              CurrentUser.username = loginUsername;
              CurrentUser.isLoggedIn = true;
              Intent myIntent = new Intent(v.getContext(), MainActivity.class);
              startActivity(myIntent);
            }
            else {
              Toast.makeText(MainActivity.this, tryLogin.trim(), Toast.LENGTH_LONG).show();
            }
          }
          catch (Exception e) {
            Toast.makeText(MainActivity.this, tryLogin.trim(), Toast.LENGTH_LONG).show();
          }
        }
      });

      /*
       * Sets up the Facebook button
       */
      facebookLogin.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
          Toast.makeText(MainActivity.this, "facebook login", Toast.LENGTH_LONG).show();
        }
      });
      dialog.show();
      return true;
    default:
      return false;
    }
  }

  /**
   * A {@link FragmentPagerAdapter} that returns a fragment corresponding to one of the primary
   * sections of the app.
   */
  public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
      super(fm);
    }

    @Override
    public Fragment getItem(int i) {
      Fragment fragment = new DummySectionFragment();
      Bundle args = new Bundle();
      args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1);
      fragment.setArguments(args);
      return fragment;
    }

    @Override
    public int getCount() {
      return 4;
    }

    @Override
    public CharSequence getPageTitle(int position) {
      switch (position) {
      case 0:
        return getString(R.string.title_section1).toUpperCase();
      case 1:
        return getString(R.string.title_section2).toUpperCase();
      case 2:
        return getString(R.string.title_section3).toUpperCase();
      case 3:
        return getString(R.string.title_section4).toUpperCase();
      }
      return null;
    }
  }
}
